/**
 * Created by no1 on 2015/11/3.
 */
'use strict';
let DD = require('./daoLoader');
let F = require('../function')
let Base = require('./Base');
let util = require("util");
let sellUserDao = new DD.mongoDB.SellUserDao();
let mysqlUsetDao = new DD.mysqlDB.UserDao()
let authorityDao = new DD.redisDB.AuthorityDao;


/**
 * 获取用户权限的详情情况(用户名称 , 归属后台,角色 ,角色权);
 * @param uid
 */
let getUserAll = function*(uid) {
  let retData = {};

  //查询用户管理表
  let retSellUser = yield getOneSellUser(uid);
  if (retSellUser.error == 1) return F.returnData(1, retSellUser.msg);
  //查询角色
  let retRole = yield F.getDataFromDispatcher('sellRoleDispatcher', 'findByDis', {rid: retSellUser.data.rid});
  if (retRole.error == 1 || retRole.data.length == 0) return F.returnData(1, '没有该角色');

  let oneRole = retRole.data[0];
  retData.permissionCodes = oneRole.permissionCodes;
  retData.name = retSellUser.data.name;
  retData.roleName = oneRole.name;
  retData.primary = retSellUser.data.primary;
  retData.id = retSellUser.data.id;
  retData.userMobile = retSellUser.data.mobile;
  retData.sid = retSellUser.data.sid;
  retData.rid = retSellUser.data.rid;
  retData.status = retSellUser.data.status;
  retData.vid = retSellUser.data.vid;

  //查询商家
  let retVendor = yield F.getDataFromDispatcher('vendorDispatcher', 'findByDis', {id: retRole.data[0].vid, status: 1});
  if (retVendor.error == 1 || retVendor.data.length == 0) return F.returnData(1, '没有该商家');

  retData.vendorType = retVendor.data[0].type || 2;

  //查询
  return F.returnData(0, "ok", retData);
}
/**
 * 获取一个关联信息
 * @param uid
 * @param status
 * @returns {*}
 */
let getOneSellUser = function*(uid) {
  let arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;
  let retSellUser = yield sellUserDao.getByQuery({uid: uid}, opt);
  if (retSellUser.error == 1 || retSellUser.data.length == 0) return F.returnData(1, '该用户还没关联', []);
  return F.returnData(0, '查询关联用户成功', retSellUser.data[0]);
}
/**
 * 获取个人信息
 * @param uid
 */
let getUserByRedis = function* (uid) {
  //查询缓存中该用户信息
  let user = yield authorityDao.find('sellUser:' + uid);

  if (!user.data) {
    user = yield getUserAll(uid);
    if (user.error == 1) return F.returnData(1, user.msg);
    yield authorityDao.save('sellUser:' + uid, JSON.stringify(user.data));
    user = yield authorityDao.find('sellUser:' + uid);
  }
  return F.returnData(0, 'ok', JSON.parse(user.data));
}


function SellUserDispatcher(data) {
  data = data || {};
  data.dao = data.dao || sellUserDao;
  data.esDao = data.esDao || {};
  data.redisDao = data.redisDao || {};
  data.modelName = data.modelName || 'sellUser';
  data.modelType = data.modelType || 'mongo';
  this.data = data;
  Base.call(this, this.data);
};
util.inherits(SellUserDispatcher, Base);

/**
 * todo 添加用户对角色的关联
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellUserDispatcher.prototype.add = function*(fields) {
  if ((!fields.rid) || (!fields.uid)) return F.returnData(1, '必须有rid或uid');

  let parameters = {};
  parameters.rid = fields.rid;
  parameters.uid = fields.uid;
  parameters.sid = 0;
  parameters.name = fields.name || '';
  //parameters.mobile = fields.mobile + "";
  parameters.status = 1;
  parameters.primary = fields.primary || 0;

  //查询uid
  let retUser = yield mysqlUsetDao.findById(parameters.uid);
  if (retUser.error == 1) return F.returnData(1, '没有该用户');
  parameters.mobile = retUser.data.mobile + "";


  //查询rid
  let retRole = yield F.getDataFromDispatcher('sellRoleDispatcher', 'findByDis', {rid: parameters.rid, status: 1});
  if (retRole.error == 1 || retRole.data.length == 0) return F.returnData(1, '没有该角色');
  parameters.vid = retRole.data[0].vid;


  //保存
  let ret = yield this.dao.findAndSave({uid: parameters.uid}, parameters);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);

  let json = JSON.parse(JSON.stringify(ret.data));
  let retData = F.dataFilter(json, ['_id', 'createdAt', 'updateAt', '__v', 'status']);
  return F.returnData(0, ret.msg, retData);
};

/**
 * todo 更新
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellUserDispatcher.prototype.update = function*(fields) {
  if (!fields.id) return F.returnData(1, '必须有id');
  let id = fields.id;
  let retSellUesr
  if (!!id) {
    retSellUesr = yield this.dao.getOneByQuery({id: id});
    if (retSellUesr.error == 1 || retSellUesr.data == {}) return F.returnData(1, '没有这个id');
  }
  let parameters = {};
  if (!!fields.name) parameters.name = fields.name;
  if (!!fields.mobile) parameters.mobile = fields.mobile;
  if (fields.status != null) parameters.status = fields.status;
  if (fields.sid != null) parameters.sid = fields.sid;
  //if (!!fields.mobile) parameters.mobile = fields.mobile + "";
  //检验uid
  if (!!fields.uid) {
    let retUsers = yield mysqlUsetDao.findById(fields.uid);
    if (retUsers.error == 1) return F.returnData(1, '用户不存在');
    parameters.uid = fields.uid;
  }
  //检验rid
  if (!!fields.rid) {
    let retSellRole = yield F.getDataFromDispatcher('sellRoleDispatcher', 'findByDis', {rid: fields.rid});
    console.log(retSellRole);
    if (retSellRole.error == 1 || retSellRole.data.length != 1) return F.returnData(1, '角色不存在');
    parameters.rid = fields.rid;
    parameters.vid = retSellRole.data[0].vid;
  }
  if (!!fields.primary) parameters.primary = fields.primary;
  let ret = yield this.dao.findAndUpdate({id: fields.id}, parameters, false);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  yield authorityDao.save('sellUser:' + retSellUesr.data.uid, '');
  return F.returnData(0, ret.msg, ret.data);
}

/**
 * 更新用户信息,对ellUser表操作.
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellUserDispatcher.prototype.updateUserInfo = function*(fields) {
  if (!fields.uid) return F.returnData(1, '必须有uid');
  let retSellUser = yield this.dao.getByQuery({uid: fields.uid});
  if (retSellUser.error == 1 || retSellUser.data.length != 1) return F.returnData(1, '该有用户还没关联');
  let parameters = {};
  if (!!fields.name) parameters.name = fields.name;
  if (!!fields.mobile) parameters.mobile = fields.mobile + "";

  let ret = yield this.dao.findAndUpdate({uid: fields.uid}, parameters, false);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  yield authorityDao.save('role:' + retSellUser.data.uid, '');
  return F.returnData(0, ret.msg, ret.data);
}

/**
 * todo 获取列表
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellUserDispatcher.prototype.list = function*(fields) {
  if (!fields.vid) return F.returnData(1, '必须有商家id');
  let isPaging = 0;
  if (fields.isPaging == 1)isPaging = fields.isPaging;

  let page = fields.page
    , pageSize = fields.pageSize
    , vid = fields.vid
    , retData = {}
    , retDataList = []
    , arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt']
    , opt = {}
    , count = {}
    , retSellUser;

  for (let one of arrDel) opt[one] = 0;

  //查询角色
  let retRole = yield F.getDataFromDispatcher('sellRoleDispatcher', 'findByDis', {vid: vid, status: 1});
  if (retRole.error == 1 || retRole.data.length == 0) return F.returnData(1, '没有角色');

  let Que = {
    vid: vid,
    status: 1,
    primary: 0
  };
  if (fields.rid != null) Que.rid = fields.rid
  if (!!fields.exclude && fields.exclude.rids.length > 0) {
    let ninRids = fields.exclude.rids;
    Que.rid = {$nin: ninRids};
  }
  //默认查询
  if (fields.act == 1) {
    //查询用户
    retSellUser = yield this.dao.getByQuery(Que, opt, page, pageSize);
    if (retSellUser.error == 1 || retSellUser.data.length == 0) return F.returnData(0, '没有用户', []);
    count = yield this.dao.getCountByQuery(Que);
  }
  //模糊查询名字 和 账号
  else if (fields.act == 2) {
    //查询用户
    let query = fields.query || "";
    let str = query.replace(/[\+]*[\*]*[\?]*[\$]*[\^]*[\\]*/g, '')
    str = str.split('').join('+[\\s\\S]*');
    let re = new RegExp(str, 'i');
    Que.$or = [{name: {$regex: re}}, {mobile: {$regex: re}}]

    retSellUser = yield this.dao.getByQuery(Que, opt, page, pageSize);
    if (retSellUser.error == 1 || retSellUser.data.length == 0) return F.returnData(0, 'ok', []);
    count = yield this.dao.getCountByQuery(Que);
  }

  //拼接角色名 到关联表
  for (let one of retSellUser.data) {
    for (let role of retRole.data) if (one.rid == role.rid) {
      one.roleName = role.name;
      //one.retain = role.retain;
    }
    retDataList.push(one);
  }
  if (isPaging == 1) {
    retData.list = retDataList;
    retData.count = count.data;
  } else retData = retDataList;

  return F.returnData(0, 'ok', retData);
}

SellUserDispatcher.prototype.listByQut = function*(fields) {
  let queryObj = fields.queryObj
    , opt = {}
    , arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt']
  for (let one of arrDel) opt[one] = 0;

  let ret = yield  this.dao.getByQuery(queryObj, opt);
  if (ret.error == 1) return F.returnData(1, ret.msg, ret.data);
  return F.returnData(0, ret.msg, ret.data);
}

/**
 * todo 获取详情
 * @param fields
 * @returns {{error, msg, data}|{error, msg}}
 */
SellUserDispatcher.prototype.detail = function*(fields) {
  if (!fields.uid) return F.returnData(1, '必须有用户的id');
  let retData = {};
  //act ==1 获取用户权限的详情情况(用户名称 , 归属后台,角色 ,角色权);
  if (fields.act == 1) retData = yield getUserByRedis(fields.uid);
  if (fields.act == 2) {
    let opt = {}
      , arr = ['_id', '__v']
      , parameters = {uid: fields.uid}
    for (let one of arr) opt[one] = 0;
    retData = yield this.dao.getOneByQuery(parameters, opt);
  }
  if (retData.error == 1) return F.returnData(1, retData.msg, retData.data);
  return F.returnData(0, 'ok', retData.data);
}

/**
 * 内部调用
 * @param Que
 * @returns {{error, msg, data}|{error, msg}}
 */
SellUserDispatcher.prototype.findByDis = function*(Que) {
  let arrDel = ['_id', '__v', '__t', 'createdAt', 'updateAt', 'status']
    , opt = {};
  for (let one of arrDel) opt[one] = 0;
  let ret = yield this.dao.getByQuery(Que, opt);
  if (ret.error == 1) F.returnData(1, ret.msg, ret.data);
  return F.returnData(0, ret.msg, ret.data);
}

module.exports = SellUserDispatcher;